package me.sdevil507.supports.helper;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import me.sdevil507.supports.result.ApiResultDTO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * HttpServletResponse执行返回json,支持跨域
 *
 * @author sdevil507
 */
@Slf4j
public class JsonResponseHelper {

    /**
     * 执行json返回
     *
     * @param response     响应
     * @param apiResultDTO 返回实体
     */
    public static void exec(HttpServletResponse response, int status, ApiResultDTO apiResultDTO) {
        response.setStatus(status);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        try (PrintWriter out = response.getWriter()) {
            ObjectMapper mapper = new ObjectMapper();
            out.append(mapper.writeValueAsString(apiResultDTO));
        } catch (IOException e) {
            log.error("IO异常:", e);
        }
    }
}
